#include	"unp.h"
#include 	<ctype.h>

void
sig_chld(int signo)
{
	pid_t	pid;
	int		stat;

	while ( (pid = waitpid(-1, &stat, WNOHANG)) > 0) {
		printf("child %d terminated\n", pid);
	}
	return;
}

void
str_echo(int sockfd)
{
	ssize_t		n;
	char		buf[MAXLINE];
	char		buf2[MAXLINE];
	int wordcount=0, bytecount=0, linecount=0;
	int ndx, ch;

again:
	while ( (n = read(sockfd, buf, MAXLINE)) > 0) {
		if(strcmp(buf,".\n")==0) {
			sprintf(buf2, "bytecount: %d, wordcount: %d linecount: %d\n", bytecount, wordcount, linecount);
			write(sockfd, buf2, strlen(buf2));
			return;
		}
		for(ndx=0; ndx < n; ndx++) {
			ch = buf[ndx];
			if(isspace(ch)) {
				if(ch == '\n')
					linecount++;
				bytecount++;
				wordcount++;
			}
			else
				bytecount++;
		}
		sprintf(buf2, "bytecount: %d, wordcount: %d\n", bytecount, wordcount);
		Writen(sockfd, buf, n);
		write(sockfd, buf2, strlen(buf2));
		bzero(buf, sizeof(buf));
		bzero(buf2, sizeof(buf2));
	}

	if (n < 0 && errno == EINTR)
		goto again;
	else if (n < 0)
		err_sys("str_echo: read error");
}

int
main(int argc, char **argv)
{
	int					listenfd, connfd;
	pid_t				childpid;
	socklen_t			clilen;
	struct sockaddr_in	cliaddr, servaddr;
//	void				sig_chld(int);

	listenfd = Socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family      = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port        = htons(SERV_PORT);

	Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));

	Listen(listenfd, LISTENQ);

	Signal(SIGCHLD, sig_chld);	/* must call waitpid() */

	for ( ; ; ) {
		clilen = sizeof(cliaddr);
		if ( (connfd = accept(listenfd, (SA *) &cliaddr, &clilen)) < 0) {
			if (errno == EINTR)
				continue;		/* back to for() */
			else
				err_sys("accept error");
		}

		if ( (childpid = Fork()) == 0) {	/* child process */
			Close(listenfd);	/* close listening socket */
			str_echo(connfd);	/* process the request */
			exit(0);
		}
		Close(connfd);			/* parent closes connected socket */
	}
}


